import serial
import numpy as np

class FPGAArray:
    def __init__(self, port='/dev/ttyUSB0', baudrate=115200):
        self.ser = serial.Serial(port, baudrate)
        
    def send_matrix(self, data: np.ndarray):
        """将float32矩阵量化为int8发送"""
        quantized = np.round(data * 127).astype(np.int8)
        self.ser.write(quantized.tobytes())
        
    def receive_results(self) -> np.ndarray:
        raw = self.ser.read(128)  # 8x8x2 bytes
        return np.frombuffer(raw, dtype=np.int16).reshape(8,8)
        
    def __enter__(self):
        return self
        
    def __exit__(self, *args):
        self.ser.close()

# 使用示例
with FPGAArray() as fpga:
    fpga.send_matrix(np.eye(8))
    results = fpga.receive_results()
    print(f"FPGA计算结果:\n{results}")